package com.wjw.java.thread.homework;

/**
 * 同三线程同时取钱,要保证三个线程操作账户时,线程安全的问题,不能超取钱
 */
public class HomeWork2 {
    public static void main(String[] args) {
        //Count实现了Runnable接口
        Count count = new Count();
        //t1、t2、t3线程,共用一个count对象,所以此时的this都是count,同步方法为线程安全
        Thread t1 = new Thread(count,"张三");
        Thread t2 = new Thread(count,"李四");
        Thread t3 = new Thread(count,"王五");
        t1.start();
        t2.start();
        t3.start();
    }
}
class Count implements Runnable{

    private int totalMoney = 10000;

    private boolean ifLoop = true;

    @Override
    public void run() {
        while (ifLoop){
            getMoney();
        }
    }

    //线程同步方法：此时锁对象为this
    public synchronized void getMoney(){
        System.out.println("账户余额为："+totalMoney);
        String name = Thread.currentThread().getName();
        System.out.println(name+":正在取钱");
        System.out.println("-----------------------");
        if(totalMoney == 0){
            ifLoop = false;//结束循环
            return;
        }
        totalMoney -= 1000;
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
